package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.comon.ResultInfo;
import com.itheima.reggie.comon.UserHolder;
import com.itheima.reggie.domain.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/address")
public class AddressController {
    @Autowired
    private AddressBookService addressBookService;

    //查询当前所有地址
    @GetMapping("/list")
    public ResultInfo<List<AddressBook>> findAddress() {
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getUserId, UserHolder.get().getId());
        List<AddressBook> addressBookList = addressBookService.list(wrapper);
        return ResultInfo.success(addressBookList);
    }

    //添加地址
    @PostMapping
    public ResultInfo<Object> saveAddress(@RequestBody AddressBook addressBook) {
        addressBookService.saveAddress(addressBook);
        return ResultInfo.success(null);
    }

    //根据id查询
    @GetMapping("/{id}")
    public ResultInfo<AddressBook> findById(@PathVariable("id") Long id) {
        return ResultInfo.success(addressBookService.getById(id));
    }

    //修改
    @PutMapping
    public ResultInfo<Object> updateAddress(@RequestBody AddressBook addressBook) {
        //根据id修改
        addressBookService.updateById(addressBook);
        return ResultInfo.success(null);
    }

    //删除
    @DeleteMapping
    public ResultInfo<Object> deleteAddress(@RequestParam("ids") List<Long> ids) {
        addressBookService.deleteAddress(ids);
        return ResultInfo.success(null);
    }

    //查询默认地址
    @GetMapping("/default")
    public ResultInfo<AddressBook> findDefault() {
        AddressBook addressBook = addressBookService.findDefault();
        return ResultInfo.success(addressBook);
    }

    //修改默认地址
    @PutMapping("/default")
    public ResultInfo<Object> updateAddress(@RequestBody Map<String, Long> map) {
        //获取要修改的id
        Long id = map.get("id");
        addressBookService.updateAddress(id);
        return ResultInfo.success(null);
    }
}
